package mk.edu.ii.traval;

import java.io.File;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;

import android.location.LocationManager;
import android.net.Uri;
import android.os.IBinder;

import android.widget.Toast;


public class TravalService extends Service{
	
	private Double lat; //latitude for location point
	private Double lon; //longitude for location point
	private Integer notification; // type of alert
	private Boolean enterArea=false;
	protected static final Integer RING =new Integer("0");
	protected static final Integer VIBRATE =new Integer("1");
	protected static final Integer RING_VIBRATE =new Integer("2");
	protected static final Integer LED =new Integer("3");
	
	private Float radius; //radius for location area
	private LocationManager locationManager; //location manager
	private ProximityReceiver proximityReceiver=new ProximityReceiver();
	protected static final String PROXIMITY_ALERT = new String("android.intent.action.PROXIMITY_ALERT");
	protected final Intent proximitylocationIntent = new Intent(PROXIMITY_ALERT);
	    
    private Notification newTravalNotification;
    public static final int NOTIFICATION_ID = 111;
    
    // execute on every start of the service
    @Override
	public void onStart(Intent intent, int startId) {
		//notification that the Service is started
		Context context = getApplicationContext();
		String msg = "The Service is started";
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(context, msg, duration);
		toast.show();		
		
		//get the Information from recevied Intent
		lat = new Double(intent.getDoubleExtra ("latitude",1000));
    	lon = new Double(intent.getDoubleExtra ("longitude",1000));
    	radius = new Float(intent.getFloatExtra("radius",500f));
    	notification = new Integer (intent.getIntExtra("notification", 0));
    	
    	//create IntentFilter for PROXIMITY_ALERT
    	IntentFilter filter = new IntentFilter(PROXIMITY_ALERT);
    	
    	
    	// register Receiver to hendle the Intent
    	registerReceiver(proximityReceiver, filter);
    	    	
    	// if  we have correct coordinates we start the ProximityAlert
    	// which will fire Intent if the device enter the specified area
    	// with longitude latitude radius and expiration time 
    	if(lat!=1000 && lon!=1000){
    	  		startProximityAlert();
    	}
    	
    	
	}
	@Override
	public void onCreate() {
		
	}
	@Override
	public IBinder onBind(Intent intent) {
	return null;
	}
	
	// execute when we stop the Service
	// or OS removed from stack
	@Override
	public void onDestroy() {
		
		unregisterProximityReceiver();
		
		super.onDestroy();
	}
	
	//starting the ProximityAlert
	public void startProximityAlert (){
		// reference to LocationManager
		locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    			
		// create PendingIntent based on (Intent)proximitylocationIntent
		PendingIntent proximityIntent = PendingIntent.getBroadcast(this, -1,
				proximitylocationIntent,
    	    	0);
		
		// add the ProximityAlert to the system, will fire
		// proximityIntent when the device enter the area 
		// specificate with longitude latitude and radius
		// and will be enabled for expiration ms in time
		locationManager.addProximityAlert(lat, lon,  radius, -1, proximityIntent);
	}
	
	// unregister Receiver to listening for ProximityAlert
	public void unregisterProximityReceiver(){
		if(!enterArea){
		unregisterReceiver(proximityReceiver);
		}		
		PendingIntent proximityIntent = PendingIntent.getBroadcast(this, -1,
				proximitylocationIntent,
    	    	0);
		locationManager.removeProximityAlert(proximityIntent);
	}
	
	// set notification type and fire the notification
	public void notif(){
		
		//set enterArea true deka e vo zonata
		enterArea=true;
		//notification in status bar(bar on the top) 
    	int icon = R.drawable.icon;
    	String tickerText = "You entered choosen area";
    	long when = System.currentTimeMillis();
    	newTravalNotification= new Notification(icon, tickerText, when);
    	
    	
    	//reference to Notification Manager
    	String svcName = Context.NOTIFICATION_SERVICE;
    	NotificationManager notificationManager;
    	notificationManager = (NotificationManager)getSystemService(svcName);
    	
    	//crating Notification layout when Status Bar is expanded (text,title,icon)
    	Context context = getApplicationContext();
    	String expandedText = "Traval-Notification";
    	String expandedTitle = "Traval:" + " ";
    	
    	// creating Intent that fire when we click on Notification 
    	Intent startActivityIntent = new Intent(context, MainTraval.class);
    	
    	startActivityIntent.setAction("android.intent.action.NOTIFIKACIJA");
    	PendingIntent launchIntent = PendingIntent.getActivity(context,
    	0,
    	startActivityIntent,
    	Intent.FLAG_ACTIVITY_NEW_TASK);
    	newTravalNotification.setLatestEventInfo(context,
    	expandedTitle,
    	expandedText,
    	launchIntent);
    	newTravalNotification.when = java.lang.System.currentTimeMillis();
    	
    	// set ringtone location if is choose Ring and Vibrate notifiaction
    	if(notification.equals(RING) || notification.equals(RING_VIBRATE)){
    		String uriStr = "android.resource://mk.edu.ii.traval/"+R.raw.submarine;
    		Uri uri = Uri.parse(uriStr);
    		//Uri ringURI = Uri.fromFile(new File("@raw/submarine"));
    		//android.provider.Settings.System.DEFAULT_RINGTONE_URI ;
    		newTravalNotification.sound = uri;
    	}
    	
    	//set vibration parametars if is choose Vibrate notifiaction
    	if(notification.equals(RING_VIBRATE) || notification.equals(VIBRATE)){
    		long[] vibrate = new long[] { 1000, 1000, 1000, 1000, 1000 };
    		newTravalNotification.vibrate = vibrate;
    	}
    	
    	//set LED for notification if is choosen LED notification
    	if(notification.equals(LED)){
    		newTravalNotification.ledARGB = Color.RED;
    		newTravalNotification.ledOffMS = 0;
    		newTravalNotification.ledOnMS = 1;
    		newTravalNotification.flags = newTravalNotification.flags | Notification.FLAG_SHOW_LIGHTS;
    	}
    	
    	
    	//fire the notification
    	notificationManager.notify(NOTIFICATION_ID, newTravalNotification);
    	
    	//show Intent on the SCREEN
    	String msg = "You just enter in choosen area";
		int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(context, msg, duration);
		toast.show();
    }
	
	// object from this class will wait broadcast intent of type
	// PROXIMITY_ALERT
	class ProximityReceiver extends BroadcastReceiver {
    	@Override
    	// action that will be performed
    	// when ProximityAlert will be received
    	public void onReceive(Context context, Intent intent) {
            String intentAction = intent.getAction();
            if(intentAction.equals(PROXIMITY_ALERT)){
            	// unregister the ProximityReceiver
            	unregisterProximityReceiver();
            	// start Notification
            	notif();
            }
        }
    }
}
